package com.example.controller;

import com.example.token.JwtHelper;
import com.example.token.Result;
import com.example.token.ResultCodeEnum;
import com.example.dao.loginMapper.LoginMapper;
import com.example.dto.login.UserLogin;
import com.example.dto.user.User;
import com.example.exception.BadRequestException;
import com.example.server.LoginServer;
import com.example.util.CreateVerifiCodeImage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Api(tags = "系统：系统授权接口")
public class LoginController {

    @Autowired
    private LoginServer loginServer;
    @Autowired
    private LoginMapper loginMapper;
    @ApiOperation("登录授权")
    @PostMapping(value = "/login")
    public Result login(@RequestBody UserLogin userLogin, HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>(4);
//        //密码解密
//        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, userLogin.getPassword());
        //获取验证码
        HttpSession session = request.getSession();
        String sessionVerifiCode = (String) session.getAttribute("verifiCode");
        String loginVerifiCode = userLogin.getCode();
        if ("".equals(sessionVerifiCode) || null == sessionVerifiCode) {
            throw new BadRequestException("验证码不存在或已过期");
        }
        if (!sessionVerifiCode.equalsIgnoreCase(loginVerifiCode)) {
            throw new BadRequestException("验证码错误");
        }
        // 从session域中移除现有验证码
        session.removeAttribute("verifiCode");
        // 准备一个map用户存放响应的数据
        Map<String, Object> map = new LinkedHashMap<>();
        List<User> user = loginServer.Login(userLogin);
        try {
            if (null != user) {
                // 以token的名称向客户端反馈
                map.put("token", JwtHelper.createToken(userLogin.getUsername()));
                map.put("userInfo",user);
            } else {
                throw new BadRequestException("密码错误");
            }
            return Result.ok(map);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Result.fail().message(e.getMessage());
        }
}

    @ApiOperation("获取用户信息")
    @GetMapping(value = "/info")
    public Result getInfoByToken(@ApiParam("token口令") @RequestHeader("token") String token) {
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        //从token中解析出 用户
        String UserName = JwtHelper.getUserName(token);

        Map<String, Object> map = new LinkedHashMap<>();

        List<User> user = loginServer.getByName(UserName);
        map.put("user", user);
        return Result.ok(map);
    }

    @ApiOperation(value = "获取验证码", produces = "image/jpeg")
    @GetMapping(value = "/code")
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        // 获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        // 获取图片上的验证码
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
        // 将验证码文本放入session域,为下一次验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode", verifiCode);
        // 将验证码图片响应给浏览器
        response.setContentType("image/jpeg");
        try {
            ImageIO.write(verifiCodeImage, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("文件上传统一入口")
    @PostMapping("/updateAvatar")
    public Map<String, Object> headerImgUpload(@ApiParam("头像文件") @RequestPart("multipartFile") MultipartFile multipartFile, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(4);
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String newFileName = uuid.concat(originalFilename.substring(i));

        // 保存文件 将文件发送到第三方/独立的图片服务器上,
        String portraitPath = "D:/alamin/alamin/target/classes/public/uplpad".concat(newFileName);
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 响应图片的路径
        String path = "public/upload/".concat(newFileName);
        result.put("code", 200);
        result.put("msg", "上传成功");
        return result;
    }

    @ApiOperation("退出登录")
    @DeleteMapping(value = "/logout")
    public String  logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return "redirect:/login";
//        return  null ;
    }
}
